package com.scs.application.modules.sys.controller;

import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.BaseController;
import com.scs.application.core.utils.FileUtils;
import com.scs.application.modules.project.Const;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.sys.properties.ResProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 */

@RestController
@RequestMapping("/sys/flow_instance/")
public class FlowInstanceController extends BaseController {

    @Autowired
    private ResProperties resProperties;


    /**
     * 流程实例上传附件
     *
     * @param file
     * @param flowKey
     * @return
     */
    @PostMapping("/uploadAttachment")
    public RestResult uploadAttachment(@RequestParam("file") MultipartFile file,
                                       @RequestParam("flowKey") String flowKey,
                                       @RequestParam("busId") String busId) {
        String resPath = resProperties.getRealPath();
        String attachmentSavePath = String.format("%s%s%s/", resPath, Const.FLOW_ATTACHMENT_SUBPATH, flowKey);
        String fileName = UUID.randomUUID().toString() + "." + FileUtils.getFileExtension(file.getOriginalFilename());
        try {
            File localFile = new File(attachmentSavePath + fileName);
            if (localFile.exists()) {
                localFile.mkdirs();
            }
            FileUtils.writeByteArrayToFile(localFile, file.getBytes());
        } catch (IOException ex) {
            throw new BusinessException(ex.getMessage());
        }
        String vPath = Const.FLOW_ATTACHMENT_VPATH + flowKey + "/" + fileName;

        Map map = new HashMap<String, String>();
        map.put("url", vPath);

        return RestResult.ok("上传文件成功!", map);
    }
}
